/***
 * 此service提供课程的增晒查改功能，即课程数据的关系数据库存储功能
 */
import relationalStore from '@ohos.data.relationalStore';
import Constants from "../constants/Constants"
import { Course } from '../entity/Course';
import { CourseDTO } from '../entity/CourseDTO';

class CourseService{

  private rdbStore: relationalStore.RdbStore;
  private dbName : string;

  public initCourseDB(context) {
    const STORE_CONFIG = {
      name: 'courseDB.db', // 数据库文件名
      securityLevel: relationalStore.SecurityLevel.S1 // 数据库安全级别
    };
    const SQL_CREATE_TABLE = `CREATE TABLE IF NOT EXISTS COURSE(
                              ID INTEGER PRIMARY KEY AUTOINCREMENT,
                              COURSENAME STRING NOT NULL,
                              COURSETEACHER STRING,
                              COURSECOLOR STRING,
                              COURSECREDIT STRING,
                              COURSEWEEK STRING,
                              COURSETIME STRING,
                              COURSEBEIZHU STRING,
                              COURSEPLACE STRING
                              )`

    relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => {
      if (err) {
        console.error(`创建课程表失败！ Code:${err.code}, message:${err.message}`);
        return;
      }
      console.info(`创建课程表成功！`);
      // 创建数据表
      store.executeSql(SQL_CREATE_TABLE);
      this.dbName = Constants.COURSETABLE_NAME;
      this.rdbStore = store;
    });
  }

  addCourseData(itemData : CourseDTO):number{
    let id : number = -1;
    const valueBucket = {
      "COURSENAME": itemData.courseName,
      "COURSETEACHER": itemData.courseTeacher,
      "COURSECOLOR":itemData.courseColor,
      "COURSECREDIT":itemData.courseCredit,
      "COURSEWEEK":itemData.courseWeek,
      "COURSETIME":itemData.courseTime,
      "COURSEBEIZHU":itemData.courseBeizhu,
      "COURSEPLACE":itemData.coursePlace
    };
    let promise = this.rdbStore.insert(this.dbName, valueBucket);
    promise.then((rowId) => {
      console.info(`插入数据成功, rowId = ${rowId}`);
      id = rowId;
    }).catch((err) => {
      console.error(`插入数据失败, code is ${err.code},message is ${err.message}`);
    })
    return id;
  }

  deleteCourseData(id : number):boolean{
    let statu : boolean = false;
    let predicates = new relationalStore.RdbPredicates(this.dbName);
    predicates.equalTo("ID", id);
    let promise = this.rdbStore.delete(predicates);
    promise.then((rows) => {
      console.info(`删除数据成功，Delete rows: ${rows}`);
      statu = rows > 0;
    }).catch((err) => {
      console.error(`Delete failed, code is ${err.code},message is ${err.message}`);
    })
    return statu;
  }

  deleteAllCourseData():boolean{
    let statu : boolean = false;
    const SQL_DELETE_TABLE = "DELETE FROM " + this.dbName;
    let promise = this.rdbStore.executeSql(SQL_DELETE_TABLE);
    promise.then(() => {
      statu = true;
      console.info(`数据全部删除成功.`);
    }).catch((err) => {
      console.error(`数据全部删除失败, code is ${err.code},message is ${err.message}`);
    })
    return statu;
  }

  updateCourseData(itemData : Course){
    let statu : boolean = false;
    const valueBucket = {
      "COURSENAME": itemData.courseName,
      "COURSETEACHER": itemData.courseTeacher,
      "COURSECOLOR":itemData.courseColor,
      "COURSECREDIT":itemData.courseCredit,
      "COURSEWEEK":itemData.courseWeek,
      "COURSETIME":itemData.courseTime,
      "COURSEBEIZHU":itemData.courseBeizhu,
      "COURSEPLACE":itemData.coursePlace
    };
    let predicates = new relationalStore.RdbPredicates(this.dbName);
    predicates.equalTo("ID", itemData.id);
    let promise = this.rdbStore.update(valueBucket, predicates);
    promise.then(async (rows) => {
      console.info(`Updated row count: ${rows}`);
      statu = rows > 0;
    }).catch((err) => {
      console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
    })
  }

  async queryCourseData():Promise<Array<Course>>{
    // 若要正常启动将正常启动下注释的模块取消注释，将测试专用注释掉
    //todo 正常启动使用
    let courseList : Array<Course> = [];
    let predicates = new relationalStore.RdbPredicates(this.dbName);
    let resultSet  = await this.rdbStore.query(predicates,
      ["ID", "COURSENAME", "COURSETEACHER","COURSECOLOR", "COURSECREDIT",
        "COURSEWEEK", "COURSETIME", "COURSEBEIZHU","COURSEPLACE"]);
    while (!resultSet.isAtLastRow){
      resultSet.goToNextRow();
      let id = resultSet.getLong(resultSet.getColumnIndex('ID'));
      let courseName = resultSet.getString(resultSet.getColumnIndex('COURSENAME'));
      let courseTeache = resultSet.getString(resultSet.getColumnIndex('COURSETEACHER'));
      let courseColor = resultSet.getString(resultSet.getColumnIndex('COURSECOLOR'));
      let courseCredit = resultSet.getString(resultSet.getColumnIndex('COURSECREDIT'));
      let courseWeek = resultSet.getString(resultSet.getColumnIndex('COURSEWEEK'));
      let courseTime = resultSet.getString(resultSet.getColumnIndex('COURSETIME'));
      let courseBeizhu = resultSet.getString(resultSet.getColumnIndex('COURSEBEIZHU'));
      let coursePlace = resultSet.getString(resultSet.getColumnIndex('COURSEPLACE'));
      let itemData:Course = new Course(id,courseName,courseTeache,courseColor,
        courseCredit,courseWeek,courseTime,courseBeizhu,coursePlace);
      courseList.push(itemData);
    }
    console.info("数据获取成功:"+JSON.stringify(courseList));

    // todo 预览器测试专用
    // let courseList:Array<Course> = Constants.courseList;

    return courseList;
  }

}

let courseService = new CourseService();
export default courseService as CourseService;